<template>
  <div class="app-container">
      <el-form ref="broilerForm" :rules="rules" :model="broilerForm" label-position="left" label-width="70px">

      <el-form-item label="标题" prop="title">
        <el-input v-model="broilerForm.title" />
      </el-form-item>
        <el-form-item label="设置" prop="setting">
             <el-table
              :data="broilerForm.setting"
              style="width: 100%">
              <el-table-column
                prop="symbol"
                label="合约"
                width="180">
              <template slot-scope="{row}">
                <span><el-input v-model="row.symbol" /></span>
              </template>
              </el-table-column>
              <el-table-column
                prop="exchange"
                label="交易所">
              <template slot-scope="{row}">
                <span><el-input v-model="row.exchange" /></span>
              </template>
              </el-table-column>
              <el-table-column
                prop="tradeTime"
                label="交易时间">
              <template slot-scope="{row,$index}">
                <div v-for="(trade,index) in row.tradeTime" :key="index" style="margin-bottom:10px;">
                  <el-input style="width:100px;" size="small" v-model="trade.beginTime" />-<el-input style="width:100px;" size="small" v-model="trade.endTime" />
                  <el-button type="primary" plain @click="handleTradeTimeAdd($index)">
                    新增
                  </el-button>
                  <el-button plain v-if="allowedTradeTimeRemove == true" type="danger" @click="handleTradeTimeRemove($index,trade)">
                    删除
                  </el-button>
                </div>
              </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="180">
              <template slot-scope="{row}">
                <el-button type="primary" @click="handleChannelAdd()">
                  新增
                </el-button>
                <el-button v-if="allowedSettingRemove == true" type="danger" @click="handleChannelRemove(row)">
                  删除
                </el-button>
              </template>
              </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="broilerForm.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="备注" />
        </el-form-item>
      </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCannel()">
        取消
      </el-button>
      <el-button type="primary" @click="saveBroiler()">
        确认
      </el-button>
      <el-button v-if="broilerForm.status.value === 5" type="danger" @click="handleDelete(broilerForm)">
        删除
      </el-button>
    </div>
  </div>
</template>

<script>
import {  saveBroiler, getBroilerDetail, removeBroilerByID } from '@/api/foundation/broiler'


import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'

import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      allowedSettingRemove:false,
      allowedTradeTimeRemove:false,
      roleOptions:[],
      listQuery: {
        start: 1,
        perpage: 10,
        title: undefined,
        sort: '+id'
      },
      showReviewer: false,
      broilerForm: {
        identity: undefined,
        remark: '',
        setting: [
          {
            symbol:"",
            exchange:"",
            tradeTime:[
              {
                beginTime:"900",
                endTime:"1015"
              },
              {
                beginTime:"1030",
                endTime:"1130"
              },
              {
                beginTime:"1330",
                endTime:"1500"
              },
              {
                beginTime:"2100",
                endTime:"2300"
              }
            ]
          }
        ],
        title: '',
        status: {
          value:1
        }
      },
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    let broilerID = this.$route.query && this.$route.query.broilerID
    if (broilerID !== undefined) {
      broilerID = parseInt(broilerID)
      if (!isNaN(broilerID)) {
        this.listLoading = true
        getBroilerDetail({
          "broilerID":broilerID
        }).then(response => {
          if (response.status === 200) {
            if(response.data.setting < 1){
              response.data.setting = this.broilerForm.setting
            }
            this.broilerForm = response.data
            if(this.broilerForm.setting.length > 1){
              this.allowedSettingRemove = true
            }
            console.log(this.broilerForm)
          } else {
            this.$message({
              message: response.msg,
              type: 'error'
            })
          }
        })
      }
    }
  },
  methods: {
    handleCannel() {
      this.$router.push({ path: 'broiler' })
    },
    handleTradeTimeAdd:function(index){
      console.log('新增交易时间：',index)
      this.broilerForm.setting[index].tradeTime.push({
              beginTime:"",
              endTime:""
      })
      if(this.broilerForm.setting[index].tradeTime.length > 1 && this.allowedSettingRemove == false){
        this.allowedTradeTimeRemove = true
      }
    },
    handleTradeTimeRemove:function(index,item){
      this.broilerForm.setting[index].tradeTime.forEach((row,index) => {
          if(row['beginTime'] == item['beginTime'] && row['endTime'] == item['endTime']){
            this.broilerForm.setting[index].tradeTime.splice(index,1);
          }
      });
      if(this.broilerForm.setting[index].tradeTime.length < 2){
        this.allowedTradeTimeRemove = false
      }
    },
    handleChannelAdd:function(){
      this.broilerForm.setting.push({
            symbol:undefined,
            exchange:"",
            tradeTime:[
              {
                beginTime:"900",
                endTime:"1015"
              },
              {
                beginTime:"1030",
                endTime:"1130"
              },
              {
                beginTime:"1330",
                endTime:"1500"
              },
              {
                beginTime:"2100",
                endTime:"2300"
              }
            ]
      })
      if(this.broilerForm.setting.length > 1 && this.allowedSettingRemove == false){
        this.allowedSettingRemove = true
      }
    },
    handleChannelRemove:function(item){
      this.broilerForm.setting.forEach((row,index) => {
          if(row['symbol'] == item['symbol'] && row['exchange'] == item['exchange']){
            this.broilerForm.setting.splice(index,1);
          }
      });
      if(this.broilerForm.setting.length < 2){
        this.allowedSettingRemove = false
      }
    },
    saveBroiler() {
      let _this = this
      this.$refs['broilerForm'].validate((valid) => {
        if (valid) {
          try {
              _this.broilerForm.status = _this.broilerForm.status.value
              if(_this.broilerForm.status == undefined){
                  _this.broilerForm.status = 6
              }
          } catch (error) {
            _this.broilerForm.status = 6
          }
          if(_this.broilerForm.hasOwnProperty('ID')){
            if(_this.broilerForm.ID !== undefined){
              _this.broilerForm.broilerID = _this.broilerForm.ID;
            }

          }
          _this.broilerForm.setting = JSON.stringify(_this.broilerForm.setting)
          saveBroiler(_this.broilerForm).then((response) => {
          if (response.status === 200) {
            this.$message({
              message: '操作Success',
              type: 'success'
            })
            this.$router.push({ path: 'broiler' })
          } else {
            this.$message({
              message: response.msg,
              type: 'error'
            })
          }
          })
        }
      })
    },
    handleDelete(row, index) {
      removeBroilerByID(row.ID).then(() => {
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    }
  }
}
</script>
